package com.itbbs.db.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author y
 * @date 2021-06-01-17:01
 */
@Configuration
public class DruidDataSourceConfig {

    @Resource
    private DBProperties dbProperties;

    /**
     * 装配主库数据源
     */
    @Bean("masterDataSource")
    public DataSource masterDataSource(){
       DruidDataSource dataSource = new DruidDataSource();
       dataSource.setDriverClassName(dbProperties.getDriverClassName());
       dataSource.setUrl(dbProperties.getMasterUrl());
       dataSource.setUsername(dbProperties.getUserName());
       dataSource.setPassword(dbProperties.getPassword());
       return dataSource;
    }

    /**
     * 装配从库数据源
     */
    @Bean("salveDataSource")
    public DataSource salveDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dbProperties.getDriverClassName());
        dataSource.setUrl(dbProperties.getSlaveUrl());
        dataSource.setUsername(dbProperties.getUserName());
        dataSource.setPassword(dbProperties.getPassword());
        return dataSource;
    }

    /**
     * 使用myRRoutingDataSource做动态数据源的管理
     *
     * @param masterDataSource 主库数据源
     * @param salveDataSource 从库数据源
     */
    @Bean("targetDataSource")
    public DataSource myRRoutingDataSource(
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("salveDataSource") DataSource salveDataSource){
        Map<Object,Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DBTypeEnum.MASTER,masterDataSource);
        targetDataSources.put(DBTypeEnum.SLAVE,salveDataSource);
        RoutingDataSource routingDataSource = new RoutingDataSource();
        routingDataSource.setDefaultTargetDataSource(masterDataSource);
        routingDataSource.setTargetDataSources(targetDataSources);
        return routingDataSource;
    }

}
